package org.finesys.common.log.trace.reflect.impl;

import lombok.extern.slf4j.Slf4j;
import org.finesys.common.log.trace.reflect.Reflect;
import org.finesys.common.log.trace.spi.annotation.Join;
import org.finesys.common.log.trace.util.LogstashUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Join
@Slf4j
public class HttpServletRequestReflect implements Reflect {

    @Override
    public Object reflect(Object obj) throws UnsupportedEncodingException {

        Map<String, String[]> result = new HashMap<>();
        if (Objects.isNull(obj)) {
            return result;
        }
        if (obj instanceof HttpServletRequest) {
            try {
                HttpServletRequest request = (HttpServletRequest) obj;
                request.setCharacterEncoding("UTF-8");
                Enumeration<String> parameterNames = request.getParameterNames();
                while (parameterNames.hasMoreElements()) {
                    String param = parameterNames.nextElement();
                    String[] value = request.getParameterValues(param);
                    result.put(param, value);
                }
            } catch (UnsupportedEncodingException e) {
                log.error(LogstashUtil.exceptionMarker(), "UnsupportedEncodingException", e);
            }
        }
        return result;

    }
}
